package MyFitnessPlate.TestApplication;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import MyFitnessPlate.DataSet.ParsedWeightDataSet;
import MyFitnessPlate.Handler.WeightHandler;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class HomeActivity extends Activity {
	private Double userWeight;
	//This is the user's information. I am allowing these numbers to be located here so we do not have to reload them.
	private String userFirstName;
	private Double userHeight;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_screen);
		
		setUserInformation();		//Set the basic account information based on the parent's intent.
		loadStaticInformation();	//Set the static home activity information. This will not be refreshed.
		loadDynamicInformation();	//Set the dynamic home activity information.
	}

	/**
	 * This method loads the static user information. This includes the name of the user.
	 */
	private void loadStaticInformation() {
		//The user does not change as long as they are logged in.
		TextView firstNameTextView = (TextView) findViewById(R.id.firstName);
		firstNameTextView.setText("Welcome back, " + userFirstName + ".");
	}

	/**
	 * This method loads the updateable information. This includes the weight, BMI, and BMI range.
	 *  It is placed here to be reusable.
	 */
	private void loadDynamicInformation() {
		//This is more accurate/current weight data.
		getWeightEntry();
		
		Double BMI = ((userWeight) / ((userHeight) * (userHeight))) * 703;
		String BmiRange = determineBMIRange(BMI);

		// Populate home page.
		TextView weightTextView = (TextView) findViewById(R.id.weight);
		weightTextView.setText("Your current weight is: " + userWeight + " lbs.");

		String bmiForMessage = String.format("%3.1f", BMI);
		
		TextView BMITextView = (TextView) findViewById(R.id.BMI);
		BMITextView.setText("Your current BMI is: " + bmiForMessage);

		TextView BmiRangeTextView = (TextView) findViewById(R.id.BmiRange);
		BmiRangeTextView.setText("According to BMI categories, you fall under: " + BmiRange);
	}

	/**
	 * This method is used for handling errors in the catch blocks.
	 * 
	 * @param tag
	 * @param message
	 * @param e
	 */
	private void handleError(String tag, String message, Exception e) {
		Log.d(tag, message);
		e.printStackTrace();
	}
	
	private void getWeightEntry(){
    	try {
    		String userName = getParent().getIntent().getExtras().getString("userName");
			URL url = new URL("http://myfitnessplate.com/api/fetch-weight-log/username/" + userName +
							  "/key/HWGCF-YASLT-HOSEC-OZWJH-HETKJ");
			/* Get a SAXParser from the SAXPArserFactory. */
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp = spf.newSAXParser();
			/* Get the XMLReader of the SAXParser we created. */
			XMLReader xr = sp.getXMLReader();
			/* Create a new ContentHandler and apply it to the XML-Reader */
			WeightHandler myWeightHandler = new WeightHandler();
			xr.setContentHandler(myWeightHandler);
			/* Parse the xml-data from our URL. */
			xr.parse(new InputSource(url.openStream()));
			/* Parsing has finished. */
			/* Our ExampleHandler now provides the parsed data to us. */
			ArrayList<ParsedWeightDataSet> wds = myWeightHandler.getParsedData();			
			userWeight = wds.get(0).getWeight();
		} catch (MalformedURLException e) {
			handleError("URL error", "URL is incorrect", e);
		} catch (ParserConfigurationException e) {
			handleError("Parser error", "Check the parser", e);
		} catch (SAXException e) {
			handleError("SAX error", "The SAX parser failed", e);
		} catch (IOException e) {
			handleError("IO error", "Check files", e);
		} finally {}
	}
	
	/**
	 * This information is retrieved from the parent intent's extras. This means we do not need to perform an extra call to the server.
	 */
	private void setUserInformation(){
		userFirstName = getParent().getIntent().getExtras().getString("userFirstName");
		userHeight = getParent().getIntent().getExtras().getDouble("userHeight");
	}
	
	private String determineBMIRange(double BMI){
		if (BMI >= 0 && BMI <= 18.5) {
			return "Under weight";
		} else if (BMI >= 18.5 && BMI <= 24.9) {
			return "Normal";
		} else if (BMI >= 25 && BMI < 30) {
			return "Over weight";
		} else {
			return "Obese";
		}
	}
	
	public void onResume() {
		super.onResume();
		loadDynamicInformation();
	}
	
	public void onRestart(){
    	super.onRestart();
    	onResume();
    }
}